﻿using Application.Common.Interfaces;
using Common.Attributes;
using Common.Caching;
using Common.Events;
using Common.Extensions;
using Common.Services;
using Domain.Entities.Identity;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Application.Features.Users.Commands.Update;

/// <summary>
/// 修改用户状态
/// </summary>
[Description("修改状态")]
[GroupDescription(("用户管理"))]
public class UpdateUserStatusCommand : IRequest<bool>
{
    /// <summary>
    /// 用户唯一标识
    /// </summary>
    [Required(ErrorMessage = "用户唯一标识必填")]
    public long UserId { get; set; }

    /// <summary>
    /// 并发标记
    /// </summary>
    [Required(ErrorMessage = "并发标记必填的")]
    public string ConcurrencyStamp { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class UpdateUserStatusCommandHandler : IRequestHandler<UpdateUserStatusCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly ICacheService _cacheService;

    public UpdateUserStatusCommandHandler(
        IApplicationDbContext context,  ICacheService cacheService)
    {
        _context = context;
        _cacheService = cacheService;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(UpdateUserStatusCommand request, CancellationToken cancellationToken)
    {
        var user = await _context.Users
           .SingleOrDefaultAsync(x => x.Id == request.UserId && x.ConcurrencyStamp == request.ConcurrencyStamp, cancellationToken);

        user!.IsActived();
        user.AddDomainEvent(new UpdatedEvent<User>(user));
        _context.Users.Update(user!);

        return true;
    }
}